import { MarkdownType } from '../model'
import type { MarkdownBlock } from '../model'

function combineBlocks(blocks: Array<MarkdownBlock>): Array<MarkdownBlock> {
  if (blocks.length === 0) return blocks

  const combinedBlocks: Array<MarkdownBlock> = []
  let currentBlock = blocks[0]

  for (let i = 1; i < blocks.length; i++) {
    const nextBlock = blocks[i]

    // Check if the current block and the next block are both of type 'default' and are adjacent
    if (
      currentBlock.type === MarkdownType.default &&
      nextBlock.type === MarkdownType.default
    ) {
      // Merge the blocks
      currentBlock.content += `\n${nextBlock.content}`
      currentBlock.span.endLine = nextBlock.span.endLine
    } else {
      // If not mergeable, push the current block to the result and move to the next block
      combinedBlocks.push(currentBlock)
      currentBlock = nextBlock
    }
  }

  // Push the last block
  combinedBlocks.push(currentBlock)

  return combinedBlocks
}

const DATA_BLOCK = '```'
export function parseBlocks(markdown: string): Array<MarkdownBlock> {
  const blocks: MarkdownBlock[] = []
  const lines = markdown.split('\n')
  let currentBlock: MarkdownBlock | null = null

  for (let i = 0; i < lines.length; i++) {
    const line = lines[i]
    if (line.startsWith(DATA_BLOCK)) {
      if (currentBlock) {
        // End of the current block
        currentBlock.span.endLine = i
        currentBlock.content += `\n${DATA_BLOCK}`
        blocks.push(currentBlock)
        currentBlock = null
      } else {
        // Start of a new block
        const type = line.includes('custom-')
          ? MarkdownType.custom
          : MarkdownType.default
        currentBlock = {
          span: { startLine: i, endLine: i },
          content: line,
          type,
        }
      }
    } else if (currentBlock) {
      // Add line to the current block
      currentBlock.content += '\n' + line
    } else {
      // Regular line, create a default block
      blocks.push({
        span: { startLine: i, endLine: i },
        content: line,
        type: MarkdownType.default,
      })
    }
  }

  // If there's an open block at the end, close it
  if (currentBlock) {
    currentBlock.span.endLine = lines.length - 1
    blocks.push(currentBlock)
  }

  return combineBlocks(blocks)
}
